package org.lh.spider.processor;

import org.lh.spider.common.DragRuleTypeEnum;
import org.lh.spider.config.SpiderProperties;
import org.springframework.beans.factory.annotation.Autowired;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;

public abstract class CommonProcessor implements PageProcessor{
	@Autowired
	private SpiderProperties spiderProperties;
	
	@Override
	public abstract void process(Page page);
	
	@Override
	public Site getSite() {
		return Site.me().setRetryTimes(spiderProperties.getRetryTime()).setRetrySleepTime(spiderProperties.getSleepTime().intValue()).setTimeOut(spiderProperties.getTimeOut().intValue());
	}
	
	static Selectable dragData(DragRuleTypeEnum ruleTypeEnum, Selectable page, String rule){
        Selectable result = null;
        if (ruleTypeEnum == DragRuleTypeEnum.XPATH){
            result = page.xpath(rule);
        }else if(ruleTypeEnum == DragRuleTypeEnum.CSS){
            result = page.css(rule);
        }else if(ruleTypeEnum == DragRuleTypeEnum.JQUERY){
            result = page.$(rule);
        }else if(ruleTypeEnum == DragRuleTypeEnum.REGEX){
            result = page.regex(rule);
        }else{
            result = page.xpath(rule);
        }
        return result;
    }

    static String  dragDataStr(DragRuleTypeEnum ruleTypeEnum, Selectable page, String rule){
        return CommonProcessor.dragData(ruleTypeEnum, page, rule).toString();
    }
}
